package csc.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="Update", urlPatterns= {"/action"})
public class UpdateServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = req.getParameter("action");
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		String address = req.getParameter("address");
		String email = req.getParameter("email");
		if (action.equals("update")) {
			Connection con = (Connection) getServletContext().getAttribute("DBConnection");
			PreparedStatement ps = null;
			try {
				ps = con.prepareStatement("update usermanagement.users set password='"+ password +"', address='"+ address +"', email='"+ email +"' where username='"+ userName +"'");
				ps.execute();
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/adminPage.html");
				PrintWriter out = resp.getWriter();
				out.println("<font color=green>Updated</font><br/>");
				rd.include(req, resp);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new ServletException("DB Connection problem.");
			} finally {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
		} else if (action.equals("delete")) {
			String user = req.getParameter("username");
			Connection con = (Connection) getServletContext().getAttribute("DBConnection");
			PreparedStatement ps = null;
			try {
				ps = con.prepareStatement("delete from usermanagement.users where username='" + user +"'");
				ps.execute();
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/adminPage.html");
				PrintWriter out = resp.getWriter();
				out.println("<font color=green>Deleted</font><br/>");
				rd.include(req, resp);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new ServletException("DB Connection problem.");
			} finally {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	private static final long serialVersionUID = 8951037616955908284L;

}
